;$(function() {
	//初始化菜单
	//开启ie6图片 缓存
	if ($.browser.msie)
		if ($.browser.version == "6.0")
			document.execCommand("BackgroundImageCache", false, true);
	//初始化菜单
	$("#menu a.has-children:not(.switch-l3)").bind("click", function() {
		var $this = $(this);
		var child = $this.next("div");
		if ($this.data("hide")) {
			child.slideDown("fast");
			$this.addClass("main-menu-open");
			$this.data("hide", false);
		} else {
			child.slideUp("fast");
			$this.removeClass("main-menu-open");
			$this.data("hide", true);
		}
	}).data("hide", true).filter(".main-menu-open").removeData("hide").next("div").show();
	//初始化按钮Hover事件
	$(".show-filter").hover(
			function () {
				$(this).addClass("hover");
			},
			function () {
				$(this).removeClass("hover");
			}
	);
	//初始化jquery-ui datepicker
	if($)
		if($.datepicker)
		{
			$.datepicker.regional['zh-CN'] = {
					closeText : '关闭',
					prevText : '<上月',
					nextText : '下月>',
					currentText : '今天',
					monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月',
							'十月', '十一月', '十二月' ],
					monthNamesShort : [ '一', '二', '三', '四', '五', '六', '七', '八', '九', '十',
							'十一', '十二' ],
					dayNames : [ '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六' ],
					dayNamesShort : [ '周日', '周一', '周二', '周三', '周四', '周五', '周六' ],
					dayNamesMin : [ '日', '一', '二', '三', '四', '五', '六' ],
					weekHeader : '周',
					dateFormat : 'yy-mm-dd',
					firstDay : 1,
					isRTL : false,
					showMonthAfterYear : true,
					yearSuffix : '年'
				};
				$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
		}
	//全局过滤ajax请求&修改$.ajax方法
	var _$ajax = $.ajax;
	$.ajax = function (params) {
		//默认返回数据类型即为json
		if(!params.dataType)
			params.dataType = "json";
		//保存原始方法引用
		var _success = params.success;
		var _error = params.error;
		var _complete = params.complete;
		var _beforeSend = params.beforeSend;
		params.success = function (data) {
			if(data.requestResult)
				if(opresult({data: data.requestResult}) == false)
					return;
			if(_success)
				_success(data);
		};
		params.error = function () {
			//if($.util)
			//	$.util.cancelLoading();
			if(_error)
				_error();
		};
		params.complete = function () {
			//if($.util)
			//	$.util.cancelLoading();
			if(_complete)
				_complete();
		};
		params.beforeSend = function () {
			//if($.util)
			//	$.util.loading();
			if(_beforeSend)
				_beforeSend();
		};
		_$ajax(params);
	};
	//清空联系人选择框
	$(".use-account-book").val("");
	//动态控制菜单高度&body最小宽度
	function adjust() {
		var $document = $(document);
		var $window = $(window);
		var height =   $document.scrollTop() + $window.height() - 100;
		$(".mp-left-auto-height").height(height);
		//动态控制body最小宽度
		if($.browser.msie)
		{
			var $window =$(window);
			var $body = $(document.body);
			$body.width("auto");
			$window.width() <= 1000 ? $body.width(1000) : void(0);
		}
	};
	$(function () {
		adjust();
	});
	$(window).bind("scroll resize", function () {
		adjust();
	});
	//扩展验证方法&设置默认选项
	var requestCounter = 0;
	if($ && $.validator)
	{
		$.validator.addMethod("dataUnique", function (value, element, action) {
			var $input = $(element);
			var value = $input.val();
			if(value && value.length <= 0)
				return;
			var result = true;
			var params = {};
			var $element = $(element);
			var otherData = $element.data("otherParams");
			var otherObj = $element.data("_jqValidate_otherObjs");
			if(otherData)
				value += otherData;
			params[action.params.VALUE] = value;
			if(otherObj)
				$.extend(params, otherObj);
			$.util.Data.request({
					url: action.url,
					data: params,
					async: false,
					dataType: "json",
					type: "post",
					success: function (data) {
							if(data[action.data.RESULT])
								result = false;
						}
				});
			return result;
		});
		//扩展验证方法
		//数字字母下划线
		$.validator.addMethod("dataName", function (value, element) {
			if(!value || value.length <= 0)
				return true;
			return /^[\d\w_\u4e00-\u9fa5\s]+$/.test(value);
		});
		$.validator.addMethod("lteDate", function (value, element, selector) {
			if(!value || value.length <= 0)
				return true;
			var target = $(selector);
			var targetValue = target.val();
			if(!targetValue || targetValue.length <= 0)
				return true;
			var targetDate = parseInt(targetValue.split("-").join(""));
			var date = parseInt(value.split("-").join(""));
			if(date > targetDate)
				return false;
			return true;
			
		});
		$.validator.addMethod("gteDate", function (value, element, selector) {
			if(!value || value.length <= 0)
				return true;
			var target = $(selector);
			var targetValue = target.val();
			if(!targetValue || targetValue.length <= 0)
				return true;
			var targetDate = parseInt(targetValue.split("-").join(""));
			var date = parseInt(value.split("-").join(""));
			if(date < targetDate)
				return false;
			return true;
		});
		$.validator.addMethod("ltDate", function (value, element, selector) {
			if(!value || value.length <= 0)
				return true;
			var target = $(selector);
			var targetValue = target.val();
			if(!targetValue || targetValue.length <= 0)
				return true;
			var targetDate = parseInt(targetValue.split("-").join(""));
			var date = parseInt(value.split("-").join(""));
			if(date >= targetDate)
				return false;
			return true;
			
		});
		$.validator.addMethod("gtDate", function (value, element, selector) {
			if(!value || value.length <= 0)
				return true;
			var target = $(selector);
			var targetValue = target.val();
			if(!targetValue || targetValue.length <= 0)
				return true;
			var targetDate = parseInt(targetValue.split("-").join(""));
			var date = parseInt(value.split("-").join(""));
			if(date <= targetDate)
				return false;
			return true;
		});
		$.validator.addMethod("crequired", function (value, element) {
			var allowrEquiredValidate = $(element).attr("allowrEquiredValidate");
			if(allowrEquiredValidate == true)
			{
				if(!value || value.length <= 0)
					return false;
			}
			return true;
		});
		$.validator.addMethod("showedRequired", function (value, element) {
			var $element = $(element);
			var hidden = false;
			if($element.css("display") == "none")
				return false;
			$element.parents().each(function () {
				if($(this).css("display") == "none")
				{
					hidden = true;
					return false;
				}
			});
			if(hidden)
				return true;
			return value && value.length > 0;
		});
		//添加联系人下拉框验证
		$.validator.addMethod("accountBookRequired", function (value, element) {
			return value && value.length > 0;
		}, "请选择人员");
		//class验证
		$.validator.addClassRules({
			"account-book-required": {
				accountBookRequired: true
			}
    	});
		//扩展依照ClassName的验证规则
		//设置默认验证设置
		$.validator.setDefaults({
			onkeyup: false	//keyup事件不做验证
		});
		//form.use-def-validate 设置验证
		$("form.use-def-validate").each(function () {
			var $form = $(this);
			$form.data("onsubmit_fun_str", $form.attr("onsubmit"));
			$form.removeAttr("onsubmit");
		}).validate({
			ignore: ".ignore",
			submitHandler: function (form) {
				var onsubmitStr = $(form).data("onsubmit_fun_str");
				if(onsubmitStr)
				{
					if(new Function(onsubmitStr)() != false)
					{
						form.submit();
						return true;
					}
					else {
						return true;
					}
				}
				form.submit();
			}
		});
	}
	//提示用户
	//提示方法
	window.showMsg = function (params) {
		if(!params || !params.message)
			return;
		var msgbar = $("#globalMsgbar");
		if(msgbar.size() > 0)
		{
			clearTimeout(msgbar.data("timeoutKey"));
			msgbar.remove();
		}
		msgbar =  $("<div id='globalMsgbar' class='global-msgbar'>" + params.message + "</div>").appendTo(document.body);
		switch(params.type)
		{
		case "exTip":
			msgbar.addClass("exTip");
			break;
		case "slientOpTip":
			msgbar.addClass("slientOpTip");
			break;
		}
		if($.browser.msie)
			msgbar.css("position", "absolute");
		function adjustPos() {
			var $document = $(document);
			var $window = $(window);
			var elSize = {width: msgbar.outerWidth()};
			var offset = {top: $document.scrollTop(), left: $document.scrollLeft() + $window.width() / 2 - elSize.width / 2};
			msgbar.css("left", offset.left + "px");
			if($.browser.msie)
				msgbar.css("top", offset.top + "px");
		};
		adjustPos();
		$(window).bind("scroll resize", adjustPos);
		if(!params.duration || params.duration == "auto")
			params.duration = params.message.length * 200;
		if(params.duration)
			msgbar.data("timeoutKey", setTimeout(function () {
				msgbar.fadeOut(1000, function () {
					msgbar.remove();
				});
			}, params.duration));
	};
	window.opresult = function (opresult) {
		if(!opresult || !opresult.data)
			return;
		var resultNumber = parseInt(opresult.data.result);
		switch(resultNumber)
		{
		//操作成功提示
		case 0:
			if(opresult.data.message)
				showMsg({
					message: opresult.data.message,
					type: opresult.data.type
				});
			break;
		//问题提示
		case 1:
			if(opresult.data.message)
				alert(opresult.data.message);
			break;
		//返回的为结果字符串&其他情况
		default:
			var leave = false;
			switch(opresult.data.result)
			{
			case "AUTH_REQUIRED":
				leave = true;
				location.reload();
				break;
			}
			if(leave == true)
				break;
			if(opresult.data.message)
			{
				alert(opresult.data.message + "\n错误代码: " + opresult.data.result);
				return false;
			}
		}
	};
		
	$(function () {
		opresult({
			data: window._opresult || {}
		});
	});
	
	$(".use-datepicker").bind("keyup keydown", function (event) {
		if(event.keyCode == 8)
			return false;
	});
	if(window.WdatePicker)
	{
		$(".use-def-datepicker").live("click", function () {
			WdatePicker({
					dateFmt: "yyyy-MM-dd"
				});
		});
	};
	
	function getCss(url) {
		$("head").append("<link href='" + url + "' rel='stylesheet' type='text/css' />");
	};
	
	function loadCssList(urls) {
		var cssNum = urls.length;
		var loadedCssList = $("head link");
		for(var i = 0;i<cssNum;++i)
		{
			var loaded = false;
			loadedCssList.each(function () {
				if(urls[i] == $(this).attr("href"))
				{
					loaded = true;
					return false;
				}
			});
			if(loaded == false)
				getCss(urls[i]);
		}
	};
	
	function loadScriptList(urls, callback) {
		var scriptNum = urls.length;
		var loadedScriptList = $("head script");
		var unloadFlag = scriptNum;
		function _callback() {
			if(-- unloadFlag <= 0)
				if(callback)
					callback();
		};
		for(var i = 0;i<scriptNum;++i)
		{
			var loaded = false;
			loadedScriptList.each(function () {
				if(urls[i] == $(this).attr("src"))
				{
					loaded = true;
					-- unloadFlag;
					return false;
				}
			});
			if(loaded == false)
				$.getScript(urls[i], _callback);
		}
	};
	
	//初始化显示桌面按钮
	var desktopShow = false;
	$(function () {
		if(window._desktopbtn != false)
		{
			$(window).bind("beforeunload", function () {
				if(desktopShow == true)
					return "如果您有工作未完成，请点击\"隐藏桌面\"回到工作区域继续您的工作。否则离开此页面后，一切未保存的工作将会丢失，要离开吗?";
			});
			$("#_showDesktop").show().click(function () {
				if(desktopShow == false)
				{
					$(this).html("隐藏桌面");
					if(window.Desktop)
						Desktop.show(function () {
							desktopShow = true;
						});
					else
					{
						//加载所需样式文件
						loadCssList([
						             path + "/css/jquery-ui-1.8.11.custom.css",
						             path + "/css/widget-system.css"
						             ]);
						//加载所需脚本文件
						loadScriptList(
								[
								 path + "/javascript/core/jquery-ui-1.8.11.custom.min.js",
								 path + "/javascript/core/jquery-jtemplates.pack.js",
								 path + "/javascript/system/util.js",
								 path + "/javascript/system/oacore.js",
								 path + "/javascript/system/widget-system.js",
								 path + "/javascript/system/desktop.js"
								 ],
								function () {
									Desktop.show(function () {
										desktopShow = true;
									});
								});
					}
				}
				else
				{
					$(this).html("我的桌面");
					Desktop.hide(function () {
						desktopShow = false;
					});
				}
			});
		}
	});
});